package com.msmall.community.common.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;

import com.msmall.base.util.Constants;
import com.msmall.community.ApplicationManager;
import com.msmall.community.common.OnlineUser;
import com.msmall.community.common.listener.OnlineUserListener;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

public class LoginCheckInterceptor implements Interceptor {
	
	private static final long serialVersionUID = 4399227445792863322L;
	
	private static final Log log = LogFactory.getLog(LoginCheckInterceptor.class);
	
	public String intercept(ActionInvocation ai) throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession session = request.getSession();
		Long userid = (Long) session.getAttribute(Constants.SESSION_USER_ID_KEY);
		OnlineUser onlineUser = OnlineUser.getOnlineUsers().get(userid);
		
		if (onlineUser.getRole() != OnlineUser.USER_ROLE_ANONYMOUS){
			return ai.invoke();
		}
		
		StringBuffer gotoUrl = new StringBuffer();
		String ctxPath = request.getContextPath();
		log.debug("ContextPath:" + ctxPath);
		String uri = request.getRequestURI();
		uri = uri.replaceFirst(ctxPath, "");
		gotoUrl.append(uri);
		if (request.getQueryString() != null && !request.getQueryString().equals("")) {
			gotoUrl.append("?");
			gotoUrl.append(request.getQueryString().replaceAll("&", "&#38;"));
        }
		log.debug("GOTOURL:"+gotoUrl.toString());
		session.setAttribute(Constants.GOTOURL, gotoUrl.toString());
		return "login";
	}

	public void init() {
		// do nothing
		
	}
	
	public void destroy() {
		// do nothing
		
	}

}
